package cn.flying.cloud.oauth.web.github;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson2.JSONObject;

import cn.flying.cloud.base.common.vo.Rt;
import cn.flying.cloud.oauth.server.configuration.properties.GithubProperties;

/**
 * GitHub授权登录
 *
 * @author: admin
 * @date: 2023年04月15日 19:28
 * @version: 1.0
 */
//解决跨域的问题
@Controller
@RequestMapping("/oauth")
public class GithubAuthController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private GithubProperties properties;
    @Resource
    private RestTemplate restTemplate;

    /**
     * 跳转到Github的登录授权页面
     *
     * @return
     */
    @RequestMapping("/github/login")
    public void login(HttpServletResponse response) {
        String state = UUID.randomUUID().toString().replaceAll("-", "");
        String url = properties.getAuthorizeUri()
                + "?client_id=" + properties.getClientId()
                + "&redirect_uri=" + properties.getRedirectUri()
                // 用于第三方应用防止CSRF攻击
                + "&state=" + state
                + "&scope=" + properties.getScope()
                + "&allow_signup=true";
        logger.info("登录请求重定向到Github的URI：【{}】", url);
        // 请求转发
        response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", url);
        // 跨域处理
        response.setHeader("Access-Control-Allow-Origin", "*");
    }

    /**
     * Github回调
     *
     * @param request
     * @return
     */
    @RequestMapping("/github/callback")
    @ResponseBody
    public Rt callback(HttpServletRequest request) {
        logger.info("Github回调返回信息：【{}】", JSONObject.toJSONString(request.getParameterMap()));
        String code = request.getParameter("code");
        String url = properties.getTokenUri()
                + "?client_id=" + properties.getClientId()
                + "&client_secret=" + properties.getClientSecret()
                + "&code=" + code;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "application/json");

        HttpEntity<String> entity = new HttpEntity<>(headers);

        logger.info("从Github获取Token的URI：【{}】", url);
        ResponseEntity<JSONObject> tokenInfoEntity = restTemplate.postForEntity(url, entity, JSONObject.class);
        JSONObject tokenInfo = tokenInfoEntity.getBody();
        logger.info("Github返回的Token信息：【{}】", tokenInfo.toString());
        String accessToken = tokenInfo.getString("access_token");
        String scope = tokenInfo.getString("scope");
        String tokenType = tokenInfo.getString("token_type");

        HttpHeaders httpHeaders = new HttpHeaders();
        // 添加自定义的header
        httpHeaders.set("Authorization", "bearer " + accessToken);
        HttpEntity httpEntity = new HttpEntity<>(httpHeaders);

        ResponseEntity<JSONObject> userInfoEntity = restTemplate.exchange(properties.getUserInfoUri(), HttpMethod.GET, httpEntity, JSONObject.class);
        JSONObject userInfo = userInfoEntity.getBody();
        logger.info("Github返回的用户信息：【{}】", userInfo.toString());

        return Rt.success(userInfo);
    }

}
